<template>
  <div class="students-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <el-icon class="title-icon"><User /></el-icon>
            学生管理
          </h1>
          <p class="page-subtitle">管理学生信息、分组和成绩</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加学生
          </el-button>
          <el-button @click="showImportDialog">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button @click="exportStudents">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon total">
            <el-icon><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ studentStats.total }}</div>
            <div class="stat-label">总学生数</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon active">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ studentStats.active }}</div>
            <div class="stat-label">活跃学生</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon groups">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ studentStats.groups }}</div>
            <div class="stat-label">分组数量</div>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon average">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ studentStats.averageScore }}</div>
            <div class="stat-label">平均分</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card>
        <div class="search-form">
          <div class="search-row">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索学生姓名、学号或邮箱"
              clearable
              class="search-input"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="searchForm.group"
              placeholder="选择分组"
              clearable
              class="search-select"
              @change="handleSearch"
            >
              <el-option label="全部分组" value="" />
              <el-option
                v-for="group in groups"
                :key="group.id"
                :label="group.name"
                :value="group.id"
              />
            </el-select>
            <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
              class="search-select"
              @change="handleSearch"
            >
              <el-option label="全部状态" value="" />
              <el-option label="活跃" value="active" />
              <el-option label="非活跃" value="inactive" />
              <el-option label="已禁用" value="disabled" />
            </el-select>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 学生列表 -->
    <div class="table-section">
      <el-card>
        <div class="table-header">
          <div class="table-title">
            <h3>学生列表</h3>
            <span class="total-count">共 {{ filteredStudents.length }} 名学生</span>
          </div>
          <div class="table-actions">
            <el-button
              :disabled="selectedStudents.length === 0"
              @click="batchAssignGroup"
            >
              批量分组
            </el-button>
            <el-button
              type="danger"
              :disabled="selectedStudents.length === 0"
              @click="batchDelete"
            >
              批量删除
            </el-button>
          </div>
        </div>
        
        <el-table
          :data="paginatedStudents"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="头像" width="80">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" min-width="120" />
          <el-table-column prop="studentId" label="学号" min-width="120" />
          <el-table-column prop="email" label="邮箱" min-width="180" />
          <el-table-column prop="phone" label="手机号" min-width="120" />
          <el-table-column label="分组" min-width="120">
            <template #default="{ row }">
              <el-tag v-if="row.group" type="primary" size="small">
                {{ row.group.name }}
              </el-tag>
              <span v-else class="text-gray">未分组</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getStatusType(row.status)"
                size="small"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="lastLoginTime" label="最后登录" min-width="150">
            <template #default="{ row }">
              {{ formatTime(row.lastLoginTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="注册时间" min-width="150">
            <template #default="{ row }">
              {{ formatTime(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="viewStudent(row)">
                查看
              </el-button>
              <el-button size="small" type="primary" @click="editStudent(row)">
                编辑
              </el-button>
              <el-dropdown @command="handleCommand">
                <el-button size="small">
                  更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item :command="{action: 'resetPassword', student: row}">
                      重置密码
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'changeGroup', student: row}">
                      更改分组
                    </el-dropdown-item>
                    <el-dropdown-item :command="{action: 'viewScores', student: row}">
                      查看成绩
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{action: 'toggleStatus', student: row}"
                      :divided="true"
                    >
                      {{ row.status === 'active' ? '禁用' : '启用' }}
                    </el-dropdown-item>
                    <el-dropdown-item
                      :command="{action: 'delete', student: row}"
                      class="danger-item"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredStudents.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑学生对话框 -->
    <el-dialog
      v-model="studentDialogVisible"
      :title="isEdit ? '编辑学生' : '添加学生'"
      width="600px"
    >
      <el-form
        ref="studentFormRef"
        :model="studentForm"
        :rules="studentRules"
        label-width="80px"
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="studentForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="studentForm.studentId" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="studentForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="studentForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="分组" prop="groupId">
              <el-select v-model="studentForm.groupId" placeholder="选择分组" style="width: 100%">
                <el-option label="不分组" :value="null" />
                <el-option
                  v-for="group in groups"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="studentForm.status" placeholder="选择状态" style="width: 100%">
                <el-option label="活跃" value="active" />
                <el-option label="非活跃" value="inactive" />
                <el-option label="已禁用" value="disabled" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="studentForm.password"
            type="password"
            placeholder="请输入初始密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="studentForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="studentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudent" :loading="saving">
          {{ isEdit ? '更新' : '添加' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 学生详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="selectedStudent?.name + ' - 详细信息'"
      width="800px"
    >
      <div v-if="selectedStudent" class="student-detail">
        <div class="detail-header">
          <el-avatar :size="80" :src="selectedStudent.avatar">
            <el-icon><User /></el-icon>
          </el-avatar>
          <div class="basic-info">
            <h3>{{ selectedStudent.name }}</h3>
            <p>学号: {{ selectedStudent.studentId }}</p>
            <p>邮箱: {{ selectedStudent.email }}</p>
            <el-tag :type="getStatusType(selectedStudent.status)">
              {{ getStatusText(selectedStudent.status) }}
            </el-tag>
          </div>
        </div>

        <el-tabs v-model="detailTab">
          <el-tab-pane label="基本信息" name="basic">
            <div class="info-grid">
              <div class="info-item">
                <label>姓名:</label>
                <span>{{ selectedStudent.name }}</span>
              </div>
              <div class="info-item">
                <label>学号:</label>
                <span>{{ selectedStudent.studentId }}</span>
              </div>
              <div class="info-item">
                <label>邮箱:</label>
                <span>{{ selectedStudent.email }}</span>
              </div>
              <div class="info-item">
                <label>手机号:</label>
                <span>{{ selectedStudent.phone }}</span>
              </div>
              <div class="info-item">
                <label>分组:</label>
                <span>{{ selectedStudent.group?.name || '未分组' }}</span>
              </div>
              <div class="info-item">
                <label>状态:</label>
                <el-tag :type="getStatusType(selectedStudent.status)">
                  {{ getStatusText(selectedStudent.status) }}
                </el-tag>
              </div>
              <div class="info-item">
                <label>注册时间:</label>
                <span>{{ formatTime(selectedStudent.createdAt) }}</span>
              </div>
              <div class="info-item">
                <label>最后登录:</label>
                <span>{{ formatTime(selectedStudent.lastLoginTime) }}</span>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="考试记录" name="exams">
            <el-table :data="selectedStudent.examRecords" stripe>
              <el-table-column prop="examTitle" label="考试名称" />
              <el-table-column prop="score" label="得分" width="80" />
              <el-table-column prop="totalScore" label="总分" width="80" />
              <el-table-column label="得分率" width="100">
                <template #default="{ row }">
                  {{ ((row.score / row.totalScore) * 100).toFixed(1) }}%
                </template>
              </el-table-column>
              <el-table-column prop="submitTime" label="提交时间" width="150">
                <template #default="{ row }">
                  {{ formatTime(row.submitTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="成绩统计" name="stats">
            <div class="score-stats">
              <div class="stats-cards">
                <div class="stats-card">
                  <div class="stats-value">{{ selectedStudent.examStats.totalExams }}</div>
                  <div class="stats-label">参加考试</div>
                </div>
                <div class="stats-card">
                  <div class="stats-value">{{ selectedStudent.examStats.averageScore }}</div>
                  <div class="stats-label">平均分</div>
                </div>
                <div class="stats-card">
                  <div class="stats-value">{{ selectedStudent.examStats.highestScore }}</div>
                  <div class="stats-label">最高分</div>
                </div>
                <div class="stats-card">
                  <div class="stats-value">{{ selectedStudent.examStats.passRate }}%</div>
                  <div class="stats-label">通过率</div>
                </div>
              </div>
              <div ref="scoreChart" class="score-chart"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入学生"
      width="600px"
    >
      <div class="import-content">
        <el-alert
          title="导入说明"
          type="info"
          :closable="false"
          show-icon
        >
          <p>请上传Excel文件，文件格式要求：</p>
          <ul>
            <li>第一行为表头：姓名、学号、邮箱、手机号、分组</li>
            <li>学号不能重复</li>
            <li>邮箱格式需正确</li>
            <li>分组名称需已存在</li>
          </ul>
        </el-alert>
        
        <div class="upload-section">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            accept=".xlsx,.xls"
            drag
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传xlsx/xls文件，且不超过2MB
              </div>
            </template>
          </el-upload>
        </div>
        
        <div class="template-section">
          <el-button @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            下载模板
          </el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="confirmImport"
          :loading="importing"
          :disabled="!importFile"
        >
          确认导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User, Plus, Upload, Download, Check, UserFilled, TrendCharts,
  Search, Refresh, ArrowDown, UploadFilled
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getStudentList, createStudent, updateStudent, deleteStudent } from '@/api/rbac/admin'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const importing = ref(false)
const studentDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const importDialogVisible = ref(false)
const isEdit = ref(false)
const selectedStudent = ref(null)
const selectedStudents = ref([])
const detailTab = ref('basic')
const currentPage = ref(1)
const pageSize = ref(20)
const importFile = ref(null)

const studentStats = ref({
  total: 156,
  active: 142,
  groups: 8,
  averageScore: 85.6
})

const searchForm = ref({
  keyword: '',
  group: '',
  status: ''
})

const studentForm = ref({
  name: '',
  studentId: '',
  email: '',
  phone: '',
  groupId: null,
  status: 'active',
  password: '',
  remark: ''
})

const studentRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const groups = ref([
  { id: 1, name: '计算机科学与技术1班' },
  { id: 2, name: '计算机科学与技术2班' },
  { id: 3, name: '软件工程1班' },
  { id: 4, name: '软件工程2班' }
])

const students = ref([
  {
    id: 1,
    name: '张明',
    studentId: '2021001001',
    email: 'zhangming@example.com',
    phone: '13800138001',
    avatar: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/a29fffba1a000df22d9ecfd2b7745047.png',
    group: { id: 1, name: '计算机科学与技术1班' },
    status: 'active',
    lastLoginTime: new Date(Date.now() - 86400000),
    createdAt: new Date(Date.now() - 86400000 * 30),
    examRecords: [
      {
        examTitle: '高等数学期中考试',
        score: 85,
        totalScore: 100,
        submitTime: new Date(Date.now() - 86400000 * 7)
      },
      {
        examTitle: '数据结构期末考试',
        score: 92,
        totalScore: 100,
        submitTime: new Date(Date.now() - 86400000 * 14)
      }
    ],
    examStats: {
      totalExams: 5,
      averageScore: 88.5,
      highestScore: 95,
      passRate: 100
    }
  },
  {
    id: 2,
    name: '李华',
    studentId: '2021001002',
    email: 'lihua@example.com',
    phone: '13800138002',
    avatar: '',
    group: { id: 1, name: '计算机科学与技术1班' },
    status: 'active',
    lastLoginTime: new Date(Date.now() - 3600000),
    createdAt: new Date(Date.now() - 86400000 * 25),
    examRecords: [
      {
        examTitle: '高等数学期中考试',
        score: 78,
        totalScore: 100,
        submitTime: new Date(Date.now() - 86400000 * 7)
      }
    ],
    examStats: {
      totalExams: 3,
      averageScore: 82.3,
      highestScore: 89,
      passRate: 100
    }
  }
])

// 计算属性
const filteredStudents = computed(() => {
  let result = students.value
  
  if (searchForm.value.keyword) {
    const keyword = searchForm.value.keyword.toLowerCase()
    result = result.filter(student => 
      student.name.toLowerCase().includes(keyword) ||
      student.studentId.toLowerCase().includes(keyword) ||
      student.email.toLowerCase().includes(keyword)
    )
  }
  
  if (searchForm.value.group) {
    result = result.filter(student => student.group?.id === searchForm.value.group)
  }
  
  if (searchForm.value.status) {
    result = result.filter(student => student.status === searchForm.value.status)
  }
  
  return result
})

const paginatedStudents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredStudents.value.slice(start, end)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const resetSearch = () => {
  searchForm.value = {
    keyword: '',
    group: '',
    status: ''
  }
  currentPage.value = 1
}

const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const getStatusType = (status) => {
  const types = {
    active: 'success',
    inactive: 'warning',
    disabled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    active: '活跃',
    inactive: '非活跃',
    disabled: '已禁用'
  }
  return texts[status] || '未知'
}

const formatTime = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

const showAddDialog = () => {
  isEdit.value = false
  studentForm.value = {
    name: '',
    studentId: '',
    email: '',
    phone: '',
    groupId: null,
    status: 'active',
    password: '',
    remark: ''
  }
  studentDialogVisible.value = true
}

const editStudent = (student) => {
  isEdit.value = true
  studentForm.value = {
    id: student.id,
    name: student.name,
    studentId: student.studentId,
    email: student.email,
    phone: student.phone,
    groupId: student.group?.id || null,
    status: student.status,
    password: '',
    remark: student.remark || ''
  }
  studentDialogVisible.value = true
}

const saveStudent = async () => {
  try {
    saving.value = true
    
    if (isEdit.value) {
      // TODO: 调用更新学生API
      // const response = await updateStudentApi(currentStudent.value.id, studentForm.value)
      // if (response.code === 0) {
      //   studentDialogVisible.value = false
      //   ElMessage.success('学生信息更新成功')
      //   await loadStudents()
      // } else {
      //   ElMessage.error(response.message || '更新失败')
      // }
      
      // 临时实现：直接更新本地数据
      Object.assign(currentStudent.value, studentForm.value)
      studentDialogVisible.value = false
      ElMessage.success('学生信息更新成功')
    } else {
      // TODO: 调用创建学生API
      // const response = await createStudentApi(studentForm.value)
      // if (response.code === 0) {
      //   studentDialogVisible.value = false
      //   ElMessage.success('学生添加成功')
      //   await loadStudents()
      // } else {
      //   ElMessage.error(response.message || '添加失败')
      // }
      
      // 临时实现：直接添加到本地数据
      students.value.unshift({
        ...studentForm.value,
        id: Date.now(),
        status: 'active',
        createdAt: new Date().toISOString().split('T')[0]
      })
      studentDialogVisible.value = false
      ElMessage.success('学生添加成功')
    }
  } catch (error) {
    console.error('保存学生信息失败:', error)
    ElMessage.error('操作失败')
  } finally {
    saving.value = false
  }
}

const viewStudent = (student) => {
  selectedStudent.value = student
  detailDialogVisible.value = true
  nextTick(() => {
    initScoreChart()
  })
}

const handleCommand = async (command) => {
  const { action, student } = command
  
  switch (action) {
    case 'resetPassword':
      await resetPassword(student)
      break
    case 'changeGroup':
      await changeGroup(student)
      break
    case 'viewScores':
      viewStudent(student)
      break
    case 'toggleStatus':
      await toggleStatus(student)
      break
    case 'delete':
      await handleDeleteStudent(student)
      break
  }
}

const resetPassword = async (student) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置 ${student.name} 的密码吗？`,
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用重置密码API
    // const response = await resetStudentPassword(student.id)
    // if (response.code === 0) {
    //   ElMessage.success('密码重置成功，新密码已发送到学生邮箱')
    // } else {
    //   ElMessage.error(response.message || '重置密码失败')
    // }
    
    // 临时实现：直接提示成功
    ElMessage.success('密码重置成功，新密码已发送到学生邮箱')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败')
    }
  }
}

const changeGroup = async (student) => {
  // 实现更改分组逻辑
  ElMessage.info('更改分组功能开发中')
}

const toggleStatus = async (student) => {
  try {
    const action = student.status === 'active' ? '禁用' : '启用'
    await ElMessageBox.confirm(
      `确定要${action} ${student.name} 吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用切换学生状态API
    // const newStatus = student.status === 'active' ? 'disabled' : 'active'
    // const response = await updateStudent(student.id, { status: newStatus })
    // if (response.code === 0) {
    //   student.status = newStatus
    //   ElMessage.success(`${action}成功`)
    // } else {
    //   ElMessage.error(response.message || `${action}失败`)
    // }
    
    // 临时实现：直接更新本地状态
    student.status = student.status === 'active' ? 'disabled' : 'active'
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('切换学生状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const handleDeleteStudent = async (student) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除学生 ${student.name} 吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用删除学生API
    // const response = await deleteStudentApi(student.id)
    // if (response.code === 0) {
    //   const index = students.value.findIndex(s => s.id === student.id)
    //   if (index > -1) {
    //     students.value.splice(index, 1)
    //   }
    //   ElMessage.success('删除成功')
    // } else {
    //   ElMessage.error(response.message || '删除失败')
    // }
    
    // 临时实现：直接从本地数据中移除
    const index = students.value.findIndex(s => s.id === student.id)
    if (index > -1) {
      students.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const batchAssignGroup = () => {
  ElMessage.info('批量分组功能开发中')
}

const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedStudents.value.length} 名学生吗？此操作不可恢复！`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用批量删除学生API
    // const studentIds = selectedStudents.value.map(s => s.id)
    // const response = await batchDeleteStudents(studentIds)
    // if (response.code === 0) {
    //   // 从本地数据中移除已删除的学生
    //   students.value = students.value.filter(s => !studentIds.includes(s.id))
    //   ElMessage.success('批量删除成功')
    //   selectedStudents.value = []
    // } else {
    //   ElMessage.error(response.message || '批量删除失败')
    // }
    
    // 临时实现：直接从本地数据中移除
    const studentIds = selectedStudents.value.map(s => s.id)
    students.value = students.value.filter(s => !studentIds.includes(s.id))
    ElMessage.success('批量删除成功')
    selectedStudents.value = []
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除学生失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const showImportDialog = () => {
  importDialogVisible.value = true
  importFile.value = null
}

const handleFileChange = (file) => {
  importFile.value = file
}

const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                  file.type === 'application/vnd.ms-excel'
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('文件大小不能超过2MB！')
    return false
  }
  return false // 阻止自动上传
}

const downloadTemplate = () => {
  ElMessage.info('正在下载模板文件...')
}

const confirmImport = async () => {
  try {
    importing.value = true
    
    // TODO: 调用导入学生API
    // const formData = new FormData()
    // formData.append('file', importFile.value)
    // const response = await importStudents(formData)
    // if (response.code === 0) {
    //   importDialogVisible.value = false
    //   ElMessage.success('导入成功')
    //   await loadStudents()
    // } else {
    //   ElMessage.error(response.message || '导入失败')
    // }
    
    // 临时实现：直接提示成功
    importDialogVisible.value = false
    ElMessage.success('导入成功')
  } catch (error) {
    console.error('导入学生失败:', error)
    ElMessage.error('导入失败')
  } finally {
    importing.value = false
  }
}

const exportStudents = () => {
  ElMessage.info('正在导出学生数据...')
}

const initScoreChart = () => {
  const chartContainer = document.querySelector('.score-chart')
  if (!chartContainer) return
  
  const chart = echarts.init(chartContainer)
  const option = {
    title: {
      text: '成绩趋势',
      left: 'center',
      textStyle: {
        fontSize: 14
      }
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['考试1', '考试2', '考试3', '考试4', '考试5']
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100
    },
    series: [
      {
        name: '得分',
        type: 'line',
        data: [78, 85, 92, 88, 95],
        smooth: true,
        itemStyle: {
          color: '#165dff'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 生命周期
onMounted(() => {
  // loadStudents()
})
</script>

<style scoped>
.students-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin: 0 0 8px 0;
}

.title-icon {
  margin-right: 12px;
  color: #165dff;
}

.page-subtitle {
  color: #86909c;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.total {
  background: #165dff;
}

.stat-icon.active {
  background: #00b42a;
}

.stat-icon.groups {
  background: #ff7d00;
}

.stat-icon.average {
  background: #722ed1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1d2129;
  margin-bottom: 4px;
}

.stat-label {
  color: #86909c;
  font-size: 14px;
}

.search-section {
  margin-bottom: 24px;
}

.search-form {
  padding: 16px;
}

.search-row {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.search-select {
  width: 150px;
}

.table-section {
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title h3 {
  margin: 0;
  color: #1d2129;
}

.total-count {
  color: #86909c;
  font-size: 14px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 16px;
}

.text-gray {
  color: #86909c;
}

.danger-item {
  color: #f53f3f;
}

.student-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e6eb;
}

.basic-info h3 {
  margin: 0 0 8px 0;
  color: #1d2129;
}

.basic-info p {
  margin: 4px 0;
  color: #86909c;
  font-size: 14px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item label {
  width: 80px;
  color: #86909c;
  font-weight: 500;
}

.info-item span {
  flex: 1;
  color: #1d2129;
}

.score-stats {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.stats-card {
  text-align: center;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #165dff;
  margin-bottom: 4px;
}

.stats-label {
  color: #86909c;
  font-size: 14px;
}

.score-chart {
  height: 300px;
}

.import-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.upload-section {
  margin: 16px 0;
}

.template-section {
  text-align: center;
}

@media (max-width: 1200px) {
  .search-row {
    flex-wrap: wrap;
  }
  
  .search-input {
    max-width: none;
    min-width: 200px;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .students-page {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .search-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .search-select {
    width: 100%;
    max-width: none;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>